<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h2>仪表盘</h2>
      <p class="dashboard-subtitle">欢迎来到Gulu Blog管理系统</p>
      <div class="dashboard-date">
        {{ currentDate }}
      </div>
    </div>
    
    <div class="dashboard-stats">
      <StatCard 
        :value="articleCount"
        label="文章总数"
        :trend="articleChange"
        :icon="FileTextOutlined"
        icon-bg-color="#1890ff"
      />
      <StatCard 
        :value="categoryCount"
        label="分类总数"
        :trend="categoryChange"
        :icon="FolderOutlined"
        icon-bg-color="#52c41a"
      />
      <StatCard 
        :value="tagCount"
        label="标签总数"
        :trend="tagChange"
        :icon="TagsOutlined"
        icon-bg-color="#faad14"
      />
      <StatCard 
        :value="viewCount"
        label="总浏览量"
        :trend="viewChange"
        :icon="EyeOutlined"
        icon-bg-color="#f5222d"
      />
    </div>
    
    <div class="dashboard-charts">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-card title="文章发布趋势" :bordered="false">
            <div ref="articleChart" style="width: 100%; height: 300px;"></div>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card title="分类文章分布" :bordered="false">
            <div ref="categoryChart" style="width: 100%; height: 300px;"></div>
          </a-card>
        </a-col>
      </a-row>
    </div>
    
    <div class="dashboard-latest-articles">
      <a-card title="最新文章" :bordered="false">
        <a-table :dataSource="latestArticles" :pagination="false">
          <a-table-column key="title" title="标题" dataIndex="title" />
          <a-table-column key="date" title="日期" dataIndex="date" />
          <a-table-column 
            key="status" 
            title="状态" 
            dataIndex="status"
            :customRender="({ text }) => {
              const color = text === 'published' ? 'green' : 'orange';
              const label = text === 'published' ? '已发布' : '草稿';
              return h('a-tag', { color }, label);
            }"
          />
          <a-table-column key="views" title="浏览量" dataIndex="views" />
        </a-table>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, h } from 'vue'
import * as echarts from 'echarts'
import { 
  FileTextOutlined, 
  FolderOutlined, 
  TagsOutlined, 
  EyeOutlined 
} from '@ant-design/icons-vue'
import StatCard from '@/components/StatCard.vue'
import settingApi from '@/api/setting'

const articleCount = ref(0)
const categoryCount = ref(0)
const tagCount = ref(0)
const viewCount = ref(0)
const articleChange = ref(0)
const categoryChange = ref(0)
const tagChange = ref(0)
const viewChange = ref(0)

// Additional stats from API
const publishedArticlesCount = ref(0)
const draftArticlesCount = ref(0)
const todayViewsCount = ref(0)
const todayArticlesCount = ref(0)
const latestArticles = ref([])

const articleChart = ref(null)
const categoryChart = ref(null)

const currentDate = ref(new Date().toLocaleDateString('zh-CN', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long'
}))

let articleChartInstance = null
let categoryChartInstance = null

const initCharts = () => {
  if (articleChart.value) {
    articleChartInstance = echarts.init(articleChart.value)
    articleChartInstance.setOption({
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: [0, 0, 0, 0, 0, 0, 0],
        type: 'line',
        smooth: true
      }]
    })
  }
  
  if (categoryChart.value) {
    categoryChartInstance = echarts.init(categoryChart.value)
    categoryChartInstance.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [{
        name: '文章数量',
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    })
  }
}

const updateArticleChart = (last7Days) => {
  if (!articleChartInstance) return
  
  const dates = last7Days.map(item => {
    const date = new Date(item.date)
    return `${date.getMonth() + 1}/${date.getDate()}`
  })
  
  const counts = last7Days.map(item => item.count)
  
  articleChartInstance.setOption({
    xAxis: {
      data: dates
    },
    series: [{
      data: counts
    }]
  })
}

const updateCategoryChart = (categoryDistribution) => {
  if (!categoryChartInstance) return
  
  const chartData = Object.entries(categoryDistribution).map(([name, value]) => ({
    name,
    value
  }))
  
  categoryChartInstance.setOption({
    series: [{
      data: chartData
    }]
  })
}

const handleResize = () => {
  if (articleChartInstance) {
    articleChartInstance.resize()
  }
  if (categoryChartInstance) {
    categoryChartInstance.resize()
  }
}

const loadDashboardData = async () => {
  try {
    const response = await settingApi.getDashboardStats()
    const data = response.data
    
    articleCount.value = data.totalArticles || 0
    categoryCount.value = data.totalCategories || 0
    tagCount.value = data.totalTags || 0
    viewCount.value = data.totalViews || 0
    articleChange.value = data.changes?.articles || 0
    categoryChange.value = data.changes?.categories || 0
    tagChange.value = data.changes?.tags || 0
    viewChange.value = data.changes?.views || 0
    
    // Update charts with API data
    updateArticleChart(data.last7Days || [])
    updateCategoryChart(data.categoryDistribution || {})
    
    // Update additional stats
    publishedArticlesCount.value = data.publishedArticles || 0
    draftArticlesCount.value = data.draftArticles || 0
    todayViewsCount.value = data.todayViews || 0
    todayArticlesCount.value = data.todayArticles || 0
    latestArticles.value = data.latestArticles || []
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
  }
}

onMounted(() => {
  loadDashboardData()
  initCharts()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (articleChartInstance) {
    articleChartInstance.dispose()
  }
  if (categoryChartInstance) {
    categoryChartInstance.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.dashboard-header {
  margin-bottom: 24px;
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.dashboard-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.dashboard-subtitle {
  margin: 0 0 12px 0;
  color: #8c8c8c;
  font-size: 14px;
}

.dashboard-date {
  color: #bfbfbf;
  font-size: 12px;
}

.dashboard-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.dashboard-charts {
  margin-top: 24px;
  margin-bottom: 24px;
}

.dashboard-additional-stats {
  margin-bottom: 24px;
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.dashboard-latest-articles {
  margin-bottom: 24px;
}

.mb-4 {
  margin-bottom: 16px;
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
  }
  
  .dashboard-stats {
    grid-template-columns: 1fr;
  }
  
  .dashboard-charts .ant-col {
    margin-bottom: 16px;
  }
}
</style>